package com.djx.commons.config.shiro;

import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.util.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.Serializable;

//该类继承了DefaultWebSessionManager 那么该类则为自定义会话类
public class CustomSessionManager extends DefaultWebSessionManager {


    //操作session,指定sessioId的获取方式
    //在前台请求头中将会有一个配置项: Authorization: Bearer 7207059FC9E817CBE61BCF579E78C73B

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String sessionId = WebUtils.toHttp(request).getHeader("Authorization");
        String requestURI = WebUtils.toHttp(request).getRequestURI();


        if(!"/sys/login".equals(requestURI) && StringUtils.isEmpty(sessionId)){ //不是登录接口
            return "";

        }else if ("/sys/login".equals(requestURI) && StringUtils.isEmpty(sessionId)){ //登录接口
            return "";
        }else{
//            sessionId = sessionId.replaceAll("djx ","");
            sessionId = sessionId.replaceAll("Bearer ","");
            //把处理后的sessionId返回
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, "header");
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return sessionId;
        }
    }
}
